<template>
  <div class="bom-container">
    <!-- 搜索栏 -->
    <div class="search-bar" style="margin-bottom: 15px;margin-left: 30px;">
      <el-input v-model="searchParams.name" style="width: 240px; padding-right: 15px;" placeholder="请输入BOM名称" />
      <el-select v-model="searchParams.productId" style="width: 240px; margin-right: 15px;" placeholder="请选择产品" clearable>
        <el-option v-for="product in productList" :key="product.id" :label="product.name" :value="product.id" />
      </el-select>
      <el-select v-model="searchParams.status" style="width: 150px; margin-right: 15px;" placeholder="请选择状态" clearable>
        <el-option label="启用" :value="1" />
        <el-option label="禁用" :value="0" />
      </el-select>
      <el-icon @click="getBomList()" style="margin-left: 20px; height: 25px; width: 25px;">
        <Search />
      </el-icon>
      <el-icon style="margin-left: 20px;" @click="resetSearchParams()">
        <Refresh />
      </el-icon>
      <el-button type="success" plain style="margin-left: 30px;" @click="showAddDialog()">创建BOM</el-button>
    </div>

    <!-- BOM表格 -->
    <el-table :data="bomList" style="width: 100%" stripe border="true">
      <el-table-column label="序号" width="80px" #default="scope" align="center">
        {{ scope.$index + 1 }}
      </el-table-column>
      <el-table-column prop="id" label="BOM ID" width="100" align="center" />
      <el-table-column prop="name" label="BOM名称" width="200" align="center" />
      <el-table-column prop="version" label="版本号" width="120" align="center" />
      <el-table-column label="产品名称" width="200" align="center">
        <template #default="scope">
          {{ getProductName(scope.row.productId) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120" #default="scope" align="center">
        <span v-if="scope.row.status == 1" style="color: green;">启用</span>
        <span v-if="scope.row.status == 0" style="color: red;">禁用</span>
      </el-table-column>
      <el-table-column label="操作" width="350px" fixed="right" align="center" #default="scope">
        <el-button type="primary" plain @click="viewBomDetails(scope.row.id)">详情</el-button>
        <el-button type="warning" plain @click="showEditDialog(scope.row)">修改</el-button>
        <el-button type="info" plain @click="showCopyDialog(scope.row)">复制</el-button>
        <el-button :type="scope.row.status === 1 ? 'danger' : 'success'" plain @click="toggleStatus(scope.row)">
          {{ scope.row.status === 1 ? '禁用' : '启用' }}
        </el-button>
        <el-button type="danger" plain @click="deleteBom(scope.row.id)">删除</el-button>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination 
        v-model:current-page="pagination.pageNum" 
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]" 
        layout="total, sizes, prev, pager, next, jumper" 
        :total="pagination.total"
        @size-change="handleSizeChange" 
        @current-change="handleCurrentChange" 
      />
    </div>

    <!-- 创建/编辑BOM对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑BOM' : '创建BOM'" width="1000px"
      :before-close="handleDialogClose" :close-on-click-modal="false">
      <el-form :model="bomForm" label-width="120px" style="padding: 15px 0;" :rules="formRules" ref="bomFormRef">
        <el-form-item label="BOM名称" prop="name">
          <el-input v-model="bomForm.name" placeholder="请输入BOM名称" />
        </el-form-item>
        <el-form-item label="产品" prop="productId">
          <el-select v-model="bomForm.productId" placeholder="请选择产品" clearable>
            <el-option v-for="product in productList" :key="product.id" :label="product.name" :value="product.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="版本号" prop="version">
          <el-input v-model="bomForm.version" placeholder="请输入版本号" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="bomForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <!-- BOM明细表格 -->
      <div style="margin: 10px 0 0 0;">
        <h4>BOM明细</h4>
        <el-table :data="bomForm.items || []" style="width: 100%; margin-bottom: 10px;">
          <el-table-column label="序号" width="60" #default="scope" align="center">
            {{ scope.$index + 1 }}
          </el-table-column>
          <el-table-column label="物料" width="200" #default="scope" align="center">
            <el-select v-model="scope.row.materialId" placeholder="请选择物料" filterable style="width: 160px">
              <el-option v-for="product in productList" :key="product.id" :label="product.name" :value="product.id" />
            </el-select>
          </el-table-column>
          <el-table-column label="用量" width="170" #default="scope" align="center">
            <el-input-number v-model="scope.row.quantity" :min="0.01" :max="999999" :step="0.01" :precision="2" controls-position="default" style="width: 120px" />
          </el-table-column>
          <el-table-column label="工艺" width="200" #default="scope" align="center">
            <el-input v-model="scope.row.process" placeholder="请输入工艺说明" />
          </el-table-column>
          <el-table-column label="操作" width="80" #default="scope" align="center">
            <el-button type="danger" size="small" @click="removeItem(scope.$index)">删除</el-button>
          </el-table-column>
        </el-table>
        <el-button type="primary" size="small" @click="addItem">添加物料</el-button>
      </div>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 复制BOM对话框 -->
    <el-dialog v-model="copyDialogVisible" title="复制BOM" width="500px" :close-on-click-modal="false">
      <el-form :model="copyForm" label-width="120px" :rules="copyRules" ref="copyFormRef">
        <el-form-item label="新BOM名称" prop="name">
          <el-input v-model="copyForm.name" placeholder="请输入新BOM名称" />
        </el-form-item>
        <el-form-item label="版本号" prop="version">
          <el-input v-model="copyForm.version" placeholder="请输入版本号" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="copyForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="copyDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCopy">确定</el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="BOM详情" width="800px" :close-on-click-modal="false">
      <div v-if="bomDetail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="BOM ID">{{ bomDetail.bom.id }}</el-descriptions-item>
          <el-descriptions-item label="BOM名称">{{ bomDetail.bom.name }}</el-descriptions-item>
          <el-descriptions-item label="版本号">{{ bomDetail.bom.version }}</el-descriptions-item>
          <el-descriptions-item label="产品名称">{{ bomDetail.product?.name }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <span v-if="bomDetail.bom.status == 1" style="color: green;">启用</span>
            <span v-if="bomDetail.bom.status == 0" style="color: red;">禁用</span>
          </el-descriptions-item>
        </el-descriptions>

        <div style="margin-top: 20px;">
          <h4>BOM明细</h4>
          <el-table :data="bomDetail.items || []" style="width: 100%;">
            <el-table-column label="序号" width="60" #default="scope" align="center">
              {{ scope.$index + 1 }}
            </el-table-column>
            <el-table-column label="物料名称" width="200" align="center">
              <template #default="scope">
                {{ getProductName(scope.row.materialId) }}
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="用量" width="120" align="center" />
            <el-table-column prop="process" label="工艺" align="center" />
          </el-table>
        </div>
      </div>

      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { bomApi } from '@/api/production/bom'
import { getProductList } from '@/api/warehouse/warehouse'

// 响应式数据
const bomList = ref([])
const productList = ref([])
const dialogVisible = ref(false)
const copyDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const isEdit = ref(false)
const bomFormRef = ref()
const copyFormRef = ref()

// 搜索参数
const searchParams = reactive({
  name: '',
  productId: null,
  status: null
})

// 分页参数
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// BOM表单
const bomForm = reactive({
  id: null,
  name: '',
  productId: null,
  version: '',
  status: 1,
  items: []
})

// 复制表单
const copyForm = reactive({
  name: '',
  version: '',
  status: 1
})

// BOM详情
const bomDetail = ref(null)
const currentCopyId = ref(null)

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入BOM名称', trigger: 'blur' }
  ],
  productId: [
    { required: true, message: '请选择产品', trigger: 'change' }
  ],
  version: [
    { required: true, message: '请输入版本号', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

const copyRules = {
  name: [
    { required: true, message: '请输入BOM名称', trigger: 'blur' }
  ],
  version: [
    { required: true, message: '请输入版本号', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 获取BOM列表
const getBomList = async () => {
  try {
    const params = {
      current: pagination.pageNum,
      size: pagination.pageSize,
      ...searchParams
    }
    
    const response = await bomApi.list(params)
    
    if (response && response.records) {
      bomList.value = response.records
      pagination.total = response.total
    } else {
      ElMessage.error('获取BOM列表失败')
    }
  } catch (error) {
    console.error('获取BOM列表失败:', error)
    ElMessage.error('获取BOM列表失败')
  }
}

// 获取产品列表
const getProductListData = async () => {
  try {
    const response = await getProductList()
    console.log('产品列表API响应:', response)
    if (response && Array.isArray(response)) {
      productList.value = response
      console.log('产品列表设置成功，共', productList.value.length, '个产品')
    } else {
      console.error('产品列表响应格式错误:', response)
    }
  } catch (error) {
    console.error('获取产品列表失败:', error)
  }
}

// 获取产品名称
const getProductName = (productId) => {
  const product = productList.value.find(p => p.id === productId)
  return product ? product.name : ''
}

// 重置搜索参数
const resetSearchParams = () => {
  Object.assign(searchParams, {
    name: '',
    productId: null,
    status: null
  })
  pagination.pageNum = 1
  getBomList()
}

// 显示新增对话框
const showAddDialog = () => {
  isEdit.value = false
  Object.assign(bomForm, {
    id: null,
    name: '',
    productId: null,
    version: '',
    status: 1,
    items: []
  })
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = async (row) => {
  isEdit.value = true
  try {
    const response = await bomApi.getDetail(row.id)
    if (response && response.success) {
      Object.assign(bomForm, {
        id: response.bom.id,
        name: response.bom.name,
        productId: response.bom.productId,
        version: response.bom.version,
        status: response.bom.status,
        items: response.items || []
      })
      dialogVisible.value = true
    } else {
      ElMessage.error('获取BOM详情失败')
    }
  } catch (error) {
    console.error('获取BOM详情失败:', error)
    ElMessage.error('获取BOM详情失败')
  }
}

// 显示复制对话框
const showCopyDialog = (row) => {
  currentCopyId.value = row.id
  Object.assign(copyForm, {
    name: row.name + '_副本',
    version: row.version + '_copy',
    status: 1
  })
  copyDialogVisible.value = true
}

// 查看BOM详情
const viewBomDetails = async (id) => {
  try {
    const response = await bomApi.getDetail(id)
    if (response && response.success) {
      bomDetail.value = response
      detailDialogVisible.value = true
    } else {
      ElMessage.error('获取BOM详情失败')
    }
  } catch (error) {
    console.error('获取BOM详情失败:', error)
    ElMessage.error('获取BOM详情失败')
  }
}

// 添加物料项
const addItem = () => {
  bomForm.items.push({
    materialId: null,
    quantity: 1,
    process: ''
  })
}

// 删除物料项
const removeItem = (index) => {
  bomForm.items.splice(index, 1)
}

// 提交表单
const submitForm = async () => {
  try {
    await bomFormRef.value.validate()
    
    const api = isEdit.value ? bomApi.update : bomApi.add
    const response = await api(bomForm)
    
    if (response && response.success) {
      ElMessage.success(isEdit.value ? 'BOM更新成功' : 'BOM创建成功')
      dialogVisible.value = false
      getBomList()
    } else {
      ElMessage.error(response?.message || '操作失败')
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage.error('操作失败')
  }
}

// 提交复制
const submitCopy = async () => {
  try {
    await copyFormRef.value.validate()
    
    const response = await bomApi.copy(currentCopyId.value, copyForm)
    
    if (response && response.success) {
      ElMessage.success('BOM复制成功')
      copyDialogVisible.value = false
      getBomList()
    } else {
      ElMessage.error(response?.message || '复制失败')
    }
  } catch (error) {
    console.error('复制BOM失败:', error)
    ElMessage.error('复制失败')
  }
}

// 删除BOM
const deleteBom = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该BOM吗？', '提示', {
      type: 'warning'
    })
    
    const response = await bomApi.delete(id)
    
    if (response && response.success) {
      ElMessage.success('删除成功')
      getBomList()
    } else {
      ElMessage.error(response?.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除BOM失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 切换状态
const toggleStatus = async (row) => {
  try {
    const response = await bomApi.toggleStatus(row.id)
    
    if (response && response.success) {
      ElMessage.success('状态更新成功')
      getBomList()
    } else {
      ElMessage.error(response?.message || '状态更新失败')
    }
  } catch (error) {
    console.error('切换状态失败:', error)
    ElMessage.error('状态更新失败')
  }
}

// 对话框关闭
const handleDialogClose = () => {
  bomFormRef.value?.resetFields()
  dialogVisible.value = false
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.pageNum = 1
  getBomList()
}

// 当前页改变
const handleCurrentChange = (current) => {
  pagination.pageNum = current
  getBomList()
}

// 初始化
onMounted(() => {
  getBomList()
  getProductListData()
})
</script>

<style scoped>
.bom-container {
  padding: 20px;
  min-height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  padding: 15px 0;
}

.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar .el-icon {
  cursor: pointer;
  color: #409eff;
}

.search-bar .el-icon:hover {
  color: #66b1ff;
}
</style>
